# 查找文件夹下的zip和rar压缩包，输出压缩包里的文件列表

import zipfile
from unrar import rarfile
import os

root = "D:/1.1_LEARN/python/文包"
mode = "OneByOne"  # AllInOne or OneByOne
dirlist = os.listdir(root)

# f = open(root+"/文包列表.txt", "a",encoding="utf-8")
# fmd=open(root+"/文包列表.md","a",encoding="utf-8")


def writeToFile(zipfile, file):
    try:
        zip_file = zipfile.encode('cp437').decode('gbk')
    except:
        zip_file = zipfile.encode('utf-8').decode('utf-8')

    # print(zip_file)

    if zip_file.find(".txt") != -1:
        if zip_file.find('/'):
            zip_file = zip_file.split('/')[-1]
        if zip_file.find('\\'):
            zip_file = zip_file.split('\\')[-1]
        file.write("- [ ] "+zip_file+"\r")
        # f.write(zip_file+"\r")
    else:
        file.write("### "+zip_file+"\r")
        # f.write(zip_file+"\r")


for fileDir in dirlist:
    if fileDir.find(".zip") != -1:  # 获取zip文件列表
        zipfileName = root+"/"+fileDir
        z = zipfile.ZipFile(zipfileName, 'r')
        list = z.namelist()
        z.close
    elif fileDir.find(".rar") != -1:  # 获取rar文件列表
        rarfileName = root+"/"+fileDir
        rar = rarfile.RarFile(rarfileName)
        list = rar.namelist()
    else:
        continue

    if mode == "OneByOne":
        filename = fileDir.split('.')[0]
        fmd = open(root+"/"+filename+".md", "a", encoding="utf-8")
    else:
        fmd = open(root+"/文包列表.md", "a", encoding="utf-8")

    print(fileDir)
    fmd.write("## "+fileDir+"\r")
    for file in list:
        writeToFile(file, fmd)
    # f.write("\r===========================================================\r\r")
    fmd.write("\r---\r")
    fmd.close()
    print("成功")

# f.close()
